<template>
	<div class="res-rooms-list-container">
		<Row>
			<Col span="4">
				<Tree :data="areaList" class="tree-data-container" @on-select-change="onSelectChange" />
			</Col>
			<Col span="20">
				<Button type="error" icon="md-add" @click="onAdd" :disabled="selectedArea.nodeLevel !== 3">新增机房</Button>
				<div class="ivu-inline-block ivu-fr">
					<Dropdown @on-click="onChangeTableSize" trigger="click">
						<Tooltip class="ivu-ml" content="密度" placement="top">
							<i-link>
								<Icon type="md-list" />
							</i-link>
						</Tooltip>
						<template #list>
							<DropdownMenu>
								<DropdownItem name="default" :selected="tableSize === 'default'">默认</DropdownItem>
								<DropdownItem name="large" :selected="tableSize === 'large'">宽松</DropdownItem>
								<DropdownItem name="small" :selected="tableSize === 'small'">紧凑</DropdownItem>
							</DropdownMenu>
						</template>
					</Dropdown>
					<Tooltip class="ivu-ml" :content="tableFullscreen ? '退出全屏' : '全屏'" placement="top">
						<i-link @click="onFullscreen">
							<Icon :custom="tableFullscreen ? 'i-icon i-icon-exit-full-screen' : 'i-icon i-icon-full-screen'" />
						</i-link>
					</Tooltip>
					<Tooltip class="ivu-ml" content="刷新" placement="top">
						<i-link @click="onRefresh">
							<Icon custom="i-icon i-icon-refresh" />
						</i-link>
					</Tooltip>
					<Dropdown trigger="click">
						<Tooltip class="ivu-ml" content="列设置" placement="top">
							<i-link>
								<Icon type="md-options" />
							</i-link>
						</Tooltip>
						<template #list>
							<DropdownMenu>
								<div class="ivu-p-8">列展示</div>
								<Divider size="small" class="ivu-mt-8 ivu-mb-8" />
								<li class="ivu-dropdown-item" v-for="item in dropdownColumns" :key="item.title"
									@click="item.show = !item.show">
									<Checkbox v-model="item.show"></Checkbox>
									<span>{{ item.title }}</span>
								</li>
							</DropdownMenu>
						</template>
					</Dropdown>
				</div>
				<Table ref="table" :columns="tableColumns" :data="list" :loading="loading" :size="tableSize" class="ivu-mt">
					<template #action="{ row }">
						<div @click.stop.prevent>
							<a style="color: #2d8cf0;" @click="onEdit(row)">编辑</a>
							<Divider type="vertical" />
							<Poptip confirm title="您确定删除该机房了吗？" transfer @on-ok="onDelete(row)">
								<a style="color: #ed4014;">删除</a>
							</Poptip>
						</div>
					</template>
				</Table>
				<div class="ivu-mt ivu-text-center">
					<Page :total="total" v-model="pageNum" show-total show-sizer show-elevator :page-size="pageSize"
						@on-change="onChangePage" @on-page-size-change="onChangePageSize" />
				</div>
			</Col>
		</Row>
		<Modal :title="modalTitle" v-model="visible" @on-cancel="onCancel" class-name="add-res-room-modal"
			:mask-closable="false" :width="800">
			<Form ref="resRoomInfo" :model="resRoomInfo" :rules="resRoomRules">
				<Row :gutter="8">
					<Col span="12">
						<FormItem label="机房名称" prop="roomName">
							<Input v-model="resRoomInfo.roomName" placeholder="请输入机房名称"/>
						</FormItem>
					</Col>
					<Col span="12">
						<FormItem label="建造时间">
							<DatePicker v-model="resRoomInfo.buildTime" transfer placeholder="请选择建造时间" />
						</FormItem>
					</Col>
					<Col span="12">
						<FormItem label="经纬度">
							<Input v-model="resRoomInfo.coordinate" placeholder="请输入经纬度"/>
						</FormItem>
					</Col>
					<Col span="12">
						<FormItem label="机房图片">
							<Upload action="" :show-upload-list="false" :max-size="20480" :format="['jpg', 'jpeg', 'png']"
								:before-upload="(file) => onBeforeUpload('pictureInfo', file)">
								<Button icon="ios-cloud-upload-outline">{{ resRoomInfo.pictureInfo || '上传' }}</Button>
							</Upload>
						</FormItem>
					</Col>
					<Col span="12">
						<FormItem label="机房仿真图">
							<Upload action="" :show-upload-list="false" :max-size="20480" :format="['jpg', 'jpeg', 'png']"
								:before-upload="(file) => onBeforeUpload('simulationImageInfo', file)">
								<Button icon="ios-cloud-upload-outline">{{ resRoomInfo.simulationImageInfo || '上传' }}</Button>
							</Upload>
						</FormItem>
					</Col>
					<Col span="12">
						<FormItem label="建造人">
							<Input v-model="resRoomInfo.buildUserName" placeholder="请输入建造人"/>
						</FormItem>
					</Col>
					<Col span="12">
						<FormItem label="监控人">
							<Select v-model="resRoomInfo.userId" placeholder="请选择建造人" clearable filterable>
								<Option v-for="item in allUsers" :value="item.userId" :key="item.userId">{{ item.name }}</Option>
							</Select>
						</FormItem>
					</Col>
					<Col span="12">
						<FormItem label="手机号" prop="phoneNo">
							<Input v-model="resRoomInfo.phoneNo" placeholder="请输入手机号" :maxlength="11"/>
						</FormItem>
					</Col>
				</Row>
			</Form>
			<template #footer>
				<Button type="text" @click="onCancel">取消</Button>
				<Button type="primary" @click="onConfirm" :loading="loading">确定</Button>
			</template>
		</Modal>
	</div>
</template>
<script>
import { compress } from 'image-conversion'
import { cloneDeep } from 'lodash'
import { RegExpConst } from '@/constants'
import { formatDate } from '@/libs/tools'
import { uploadFile } from '@/api/file'
import { getUserList } from '@api/user'
import { getAreaList } from '@/api/common'
import { getResRoomList, createResRoom, updateResRoom } from '@api/res-room'

export default {
	data() {
		return {
			loading: false,
			list: [],
			pageNum: 1,
			pageSize: 10,
			total: 0,
			tableSize: 'small',
			tableFullscreen: false,
			allUsers: [],
			modalTitle: '',
			visible: false,
			areaList: [],
			selectedArea: {},
			resRoomInfo: {
				id: '',
				roomName: '',
				buildTime: '',
				coordinate: '',
				pictureInfo: '',
				simulationImageInfo: '',
				buildUserName: '',
				userId: '',
				userName: '',
				phoneNo: ''
			},
			resRoomRules: {
				roomName: [
					{ required: true, message: `请输入机房名称` },
				],
				buildUserName: [
					{ ...RegExpConst.name }
				],
				phoneNo: [
					{ ...RegExpConst.phoneNo }
				]
			},
		}
	},
	computed: {
		columns() {
			return [
				{ title: '机房名称', key: 'roomName', width: 120 },
				{ title: '建造时间', key: 'buildTime', width: 180 },
				{ title: '经纬度', key: 'coordinate', width: 200 },
				{ title: '机房图片', key: 'pictureInfo', minWidth: 180 },
				{ title: '机房仿真图', key: 'simulationImageInfo', minWidth: 180 },
				{ title: '建造人', key: 'buildUserName', width: 80 },
				{ title: '监控人', key: 'userName', width: 80 },
				{ title: '监控人电话', key: 'phoneNo', width: 120 },
				{ title: '操作', key: 'action', slot: 'action', align: 'center', width: 120, fixed: 'right'}
			]
		},
		tableColumns() {
			const columns = [...this.columns];
			return columns
		},
		dropdownColumns() {
			return this.columns.filter(item => item.title)
		}
	},
	async mounted() {
		const response = await getAreaList({})
		this.onGenerateTree(response)
	},
	methods: {
		async getAllUsers() {
			const response = await getUserList({
				pageNum: 1,
				pageSize: 1000,
			})
			this.allUsers = response.records || [];
		},
		async getData() {
			if (this.loading) return;
			this.loading = true;
			const params = this.$parent.$parent.$refs.form.data;
			const response = await getResRoomList({
				pageSize: this.pageSize,
				pageNum: this.pageNum,
				regionId: this.selectedArea.nodeId || undefined,
				roomName: params.roomName || undefined,
				phoneNo: params.phoneNo || undefined,
			})
			this.list = response.records || [];
			this.total = response.total;
			this.loading = false;
		},
		onGenerateTree(areaList) {
			const treeData = areaList.filter(area => !area.parentId)
			for (let i = 0; i < treeData.length; i++) {
				treeData[i].expand = true
				treeData[i].children = []
				treeData[i].render = (h, { root, node, data }) => {
					return h('span', {}, data.nodeName)
				}
				cloneDeep(areaList).forEach(area => {
					if (area.parentId === treeData[i].nodeId) {
						if (!area.children) {
							area.expand = true
							area.children = []
							cloneDeep(areaList).forEach(subArea => {
								if (subArea.parentId === area.nodeId) {
									subArea.expand = true
									subArea.children = []
									subArea.render = (h, { root, node, data }) => {
										return h('span', {
											style: {
												width: '100%'
											}
										}, [
										h('span', {
												style: {
													display: 'inline-block',
													width: '80px',
												}
											}, data.nodeName),
										]);
									}
									area.children.push(subArea)
								}
							})
						}
						area.render = (h, { root, node, data }) => {
							return h('span', {
								style: {
									width: '100%'
								}
							}, [
							h('span', {
									style: {
										display: 'inline-block',
										width: '80px',
									}
								}, data.nodeName),
							]);
						}
						areaList[i].children.push(area)
					}
				})
			}
			this.areaList = treeData
		},
		onSelectChange(_, selectedArea) {
			this.selectedArea = selectedArea
			this.getData()
		},
		onChangeTableSize(size) {
			this.tableSize = size;
		},
		onFullscreen() {
			this.tableFullscreen = !this.tableFullscreen;
			this.$emit('on-fullscreen', this.tableFullscreen);
		},
		onRefresh() {
			this.getData();
		},
		onChangePage(page) {
			this.pageNum = page;
			this.getData();
		},
		onChangePageSize(size) {
			this.pageNum = 1;
			this.pageSize = size;
			this.getData();
		},
		onSearch() {
			this.pageNum = 1;
			this.getData();
		},
		async onAdd() {
			await this.getAllUsers()
			this.modalTitle = '新建机房'
			this.visible = true
		},
		async onEdit(row) {
			await this.getAllUsers()
			this.modalTitle = '编辑机房'
			this.visible = true
			this.resRoomInfo = { ...row }
		},
		async onBeforeUpload(name, file) {
			this.loading = true
      const result = await this._onBeforeUpload(file)
      if (result) {
        this.$Message.success('上传成功')
        this.resRoomInfo[name] = result
      }
			this.loading = false
		},
		_onBeforeUpload(file) {
      const supportTypes = ['jpg', 'jpeg', 'png']
      return new Promise((resolve) => {
        const FileExt = file.name.replace(/.+\./, '')
        if (file.size > 20480 * 1024) {
          this.$Message.warning('请上传20M以内的文件')
          resolve(false)
        } else if (!supportTypes.includes(FileExt.toLowerCase())) {
          this.$Message.warning(`请上传${supportTypes.join('/')}文件`)
          resolve(false)
        } else {
          compress(file, 0.6).then(res => {
            const reader = new FileReader()
            reader.readAsDataURL(res)
            reader.onload = async e => {
              const response = await uploadFile({
                base64Content: e.target.result.split(',')[1],
                fileName: file.name.split('.').slice(0, -1).join('.'),
								fileType: FileExt
              })
              resolve(response.data)
            }
            reader.onerror = () => {
              resolve(false)
            }
          })
        }
      })
    },
		onCancel() {
			this.$refs.resRoomInfo.resetFields()
			this.visible = false
			this.resRoomInfo = {
				id: '',
				roomName: '',
				buildTime: '',
				coordinate: '',
				pictureInfo: '',
				simulationImageInfo: '',
				buildUserName: '',
				userId: '',
				userName: '',
				phoneNo: ''
			}
		},
		onConfirm() {
			this.$refs.resRoomInfo.validate(async (valid) => {
				if (valid) {
					this.loading = true
					const { buildTime, userId } = this.resRoomInfo
					let response = {}
					if (this.resRoomInfo.id) {
						response = await updateResRoom({
							...this.resRoomInfo,
							buildTime: formatDate(buildTime, 'year'),
							userName: this.allUsers.find(u => u.userId === userId).name
						})
					} else {
						if (this.selectedArea.nodeLevel === 3) {
							response = await createResRoom({
								...this.resRoomInfo,
								id: undefined,
								regionId: this.selectedArea.nodeId,
								buildTime: formatDate(buildTime, 'year'),
								userName: this.allUsers.find(u => u.userId === userId).name
							})
						} else {
							this.$Message.warning('请选择局站')
						}
					}
					this.loading = false
					if (response.code === 1000) {
						this.$Message.success('操作成功')
						if (!this.resRoomInfo.id) {
							this.pageNum = 1
						}
						this.getData()
						this.onCancel()
					}
				}
			})
		},
		async onDelete(row) {
			const response = await updateResRoom({
				id: row.id,
				isDelete: 1
			})
			if (response.code === 1000) {
				this.$Message.success('删除成功')
				this.pageNum = 1
				this.getData()
			}
		}
	}
}
</script>
<style lang="less">
.add-res-room-modal {
	.ivu-form-item-label {
		width: 100%;
		text-align: left;
	}
	.ivu-date-picker {
		width: 100%;
	}
}
</style>
